#!/bin/sh

set -x

repo="$1"
repo="$(echo "$repo" | replace 'https://' '' 'github.com/' '')"
dstdir="$2"
branch="$3"
# upstream="$1"
# shift

if [ -z "$repo" ]; then
  1>&2 echo "  ghclone foo/bar"
  1>&2 echo "is shorthand for"
  1>&2 echo "  git clone https://github.com/foo/bar"
  1>&2 echo ""
  1>&2 echo "to clone to a different directory:"
  1>&2 echo "  ghclone foo/bar dstdir"
  1>&2 echo ""
  # 1>&2 echo "to also add an 'upstream' remote whose url is 'https://github.com/original/bar':"
  # 1>&2 echo "  ghclone foo/bar dstdir master original/bar"
  # 1>&2 echo ""
  # 1>&2 echo "to do all of the above and then 'git pull upstream master':"
  # 1>&2 echo "  ghclone foo/bar dstdir original/bar master"
  # 1>&2 echo ""
  exit 1
fi

if [ -z "${dstdir}" ]; then
  exec git clone --recursive "https://github.com/${repo}"
fi

if [ -e "${dstdir}" ]; then
  1>&2 echo "already exists: ${dstdir}"
  exit 1
fi

if [ -z "${branch}" ]; then
  git clone --recursive "https://github.com/${repo}" "${dstdir}"
  cd "${dstdir}"
else
  git clone --recursive "https://github.com/${repo}" "${dstdir}" -b "${branch}"
  cd "${dstdir}"
  cdbranch "${branch}"
fi

# if [ ! -z "${upstream}" ]; then
#   git remote add upstream "https://github.com/${upstream}"

#   if [ ! -z "${branch}" ]; then
#     git pull upstream "${branch}"
#   fi
# fi
  


